﻿using IServices;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using YL.Core.Dto;
using YL.Core.Entity;
using YL.NetCore.NetCoreApp;
using YL.Utils.Delegate;
using YL.Utils.Extensions;
using YL.Utils.Pub;
using YL.Utils.Security;
using YL.Utils.Table;
using Minio;
using Minio.Exceptions;
using System.Threading.Tasks;
using SqlSugar;

namespace EduCMS.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class CommentController : BaseController
    {
        private readonly IWhr_commentServices _services;
        private readonly IWhr_comment_imagesServices _commentImagesServices;
        private readonly Xss _xss;
        private readonly SqlSugarClient _client;

        public CommentController(IWhr_commentServices services, IWhr_comment_imagesServices commentImageServices, Xss xss, SqlSugarClient client) 
        {
            _services = services;
            _commentImagesServices = commentImageServices;
            _xss = xss;
            _client = client;
        }

        /// <summary>
        /// 评价
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Post([FromForm]WhrCommentDto dto) 
        {
            //图片不一定是必传,错误提示内容要改成常量
            var userId = UserDto.UserId;
            if (dto.Content is null) 
            {
                return Json(Microprogram.DataInfo(PubEnum.Failed, "评论内容不能为空", null));
            }
            if (dto.CourseId == 0) 
            {
                return Json(Microprogram.DataInfo(PubEnum.Failed, "课程ID不能为空", null));
            }
            var comment = new Whr_comment
            {
                CourseId = dto.CourseId,
                UserId = userId,
                Content = dto.Content,
                Status = 0,
                Anonymous = dto.Anonymous
            };

            var Id = _services.InsertIdentity(comment);
            if (Id <= 0) 
            {
                return Json(Microprogram.DataInfo(PubEnum.Failed, "数据插入失败", null));
            }

            if (!dto.Images.IsNullOrEmpty() && dto.Images.Count > 0) 
            {
                var cols = new List<Whr_comment_images>();
                foreach (var image in dto.Images) 
                {
                    if (image is null) continue;
                    cols.Add(new Whr_comment_images
                    {
                        CommentId = Id,
                        ImagePath = image
                    });
                }

                if (cols.Count > 0)
                {
                    var flag = _commentImagesServices.InsertTran(cols);
                    if (flag.ErrorException != null)
                    {
                        return Json(Microprogram.DataInfo(PubEnum.Failed, "图片插入失败", null));
                    }
                }
            }
            return Json(Microprogram.DataInfo(PubEnum.Success, PubConst.Add1, new { Id }));
        }
        
        /// <summary>
        /// 评论列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("list/{id}")]
        [AllowAnonymous]
        public JsonResult List(int id, [FromForm]Bootstrap.BootstrapParams bootstrap) 
        {            
            var result = _services.PageList(bootstrap, id);
            return Json(Microprogram.DataInfo(PubEnum.Success, "", Bootstrap.GridData(result.Item2, result.Item1)));
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("upload")]
        [AllowAnonymous]
        public IActionResult UploadFile(IFormFile file) 
        {
            if (file == null || file.Length <= 0) 
            {
                return Json(Microprogram.DataInfo(PubEnum.Failed, PubConst.File1, null));
            }         
            //上传的文件要判断mime类型
            string fileExt = Path.GetExtension(file.FileName).ToLower();

            var path = Path.Combine("upload", DateTimeExt.GetDateTimeS(DateTimeExt.DateTimeShortFormat), PubId.GetUuid());
            var img = path + fileExt;
            
            var savePath = Path.Combine(WebRoot, path);
            if (!Directory.Exists(savePath)) 
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(WebRoot, img);
       
            return DelegateUtil.TryExecute<IActionResult>(() => 
            {
                using (var stream = new FileStream(filePath, FileMode.CreateNew)) 
                {
                    file.CopyTo(stream);
                }
                return Json(Microprogram.DataInfo(PubEnum.Success, PubConst.File6, new { path = img }));
            }, Json(Microprogram.DataInfo(PubEnum.Failed, PubConst.File5, null)));
        }
        
        /// <summary>
        /// 上传到文件管理服务器
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("upload_minio"), AllowAnonymous]
        public async Task<IActionResult> UploadToMinio(IFormFile file)
        {
            var fileStream = file.OpenReadStream();

            //client对象链式调用.WithSSL()，可以启用https。
            var minioClient = new MinioClient(
                PubMinio.EndPoint,
                PubMinio.AccessKey,
                PubMinio.SecretKey
                ).WithSSL();

            var found = await minioClient.BucketExistsAsync(PubMinio.ImagesBucket);
            //return Json(Microprogram.DataInfo(PubEnum.Failed, "ff", found));
            if (!found)
            {
                await minioClient.MakeBucketAsync(PubMinio.ImagesBucket);
            }
            try
            {
                await minioClient.PutObjectAsync(PubMinio.ImagesBucket, file.FileName, fileStream, fileStream.Length, file.ContentType);
                var uuid = Guid.NewGuid().ToString();

                var exist = _client.Queryable<Whr_mio_file>().Where(f => f.FileName == file.FileName).First();
                if (exist == null)
                {
                    var bucketEntity = new Whr_mio_file
                    {
                        ObjectId = uuid,
                        Type = 1,
                        FileName = file.FileName,
                        BucketName = PubMinio.ImagesBucket,
                        ContentType = file.ContentType,
                    };
                    await _client.Insertable(bucketEntity).ExecuteCommandAsync();
                }
                else {
                    exist.CreateAt = DateTime.Now;
                    await _client.Updateable(exist).ExecuteCommandAsync();
                }
                
                return Json(Microprogram.DataInfo(PubEnum.Success, "上传成功", new { filename = "https://" + PubMinio.EndPoint + "/" + PubMinio.ImagesBucket + "/" + file.FileName }));
            }
            catch (MinioException e)
            {
                return Json(Microprogram.DataInfo(PubEnum.Failed, e.Message, null));
            }
        }
    }
}